﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
namespace WXFramework.Model
{
    public class CropTokenManager
    {
        public static CropTokenManager _TokenManager;




        public string access_token { get; set; }

        public static bool IsModify { get; set; }

        private static string cropid;

        public static string CropId
        {
            get { return cropid; }
            set
            {
                if (value != cropid)
                {
                    cropid = value;
                    IsModify = true;
                }
            }
        }

        private static string secret;

        public static string Secret
        {
            get { return secret; }
            set
            {
                if (value != secret)
                {
                    secret = value;
                    IsModify = true;
                }
            }
        }

        public static string StrUrl 
        {
            get 
            {
                return string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", CropId, Secret);
            }
        }

        public int expires_in { get; set; }

        private DateTime createTokenTime = DateTime.Now;

        /// <summary>
        /// 到期时间(防止时间差，提前1分钟到期)
        /// </summary>
        /// <returns></returns>
        public DateTime TookenOverdueTime
        {
            get { return createTokenTime.AddSeconds(expires_in - 60); }
        }

        /// <summary>
        /// 刷新Token
        /// </summary>
        public static void Renovate()
        {
            if (_TokenManager == null)
            {
                GetNewToken();
            }

            CropTokenManager._TokenManager.createTokenTime = DateTime.Now;
        }

        public static bool IsTimeOutOrIsModify()
        {
            if (_TokenManager == null || IsModify)
            {
                GetNewToken();
            }

            return DateTime.Now >= CropTokenManager._TokenManager.TookenOverdueTime;
        }

        public static CropTokenManager GetNewToken()
        {

            string respone = HttpHelper.HttpGet(StrUrl);

            var token = JsonConvert.DeserializeObject<CropTokenManager>(respone);

            CropTokenManager._TokenManager = token;

            IsModify = false;

            return token;
        }

        public static string GetToken()
        {
            IsTimeOutOrIsModify();
            
            return _TokenManager.access_token;
        }

        public static Dictionary<int, string> acces_Tokens { get; set; }

    }
}
